<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Util;
use common\components\services\message\ManualWechatMessage;
use common\models\datas\Admin;
use common\components\helpers\Fun;
use common\models\datas\Admissionfee;
use common\models\datas\CardAttr;
use common\models\datas\Cate;
use common\models\datas\Classhourfee;
use common\models\datas\Customer;
use common\models\datas\LoginAuth;
use common\models\datas\Site;
use doumiaoduo\buildform\BuildForm;
use EasyWeChat\Core\Exceptions\HttpException;
use EasyWeChat\Message\News;
use yii\db\Exception;
use yii\widgets\ActiveForm;
use zhtfrontend\components\helpers\Funs;
use zhtfrontend\components\services\classmanager\Operclassmanager;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\CateRelation;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\ClassManageTime;
use zhtfrontend\models\datas\ClassmanageTurn;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\ClassroomAttr;
use zhtfrontend\models\datas\ClassStudent;
use common\models\datas\DepositLog;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\GoodsPrice;
use zhtfrontend\models\datas\GoodsTeacher;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\MechanicSubsidy;
use zhtfrontend\models\datas\Orders;
use zhtfrontend\models\datas\OrdersItems;
use common\models\datas\Student;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\SubstituteCheck;
use zhtfrontend\models\datas\Teacher;
use yii\data\Pagination;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\helpers\Html;
use EasyWeChat\Foundation\Application;

class NewclassmanageController extends \zhtfrontend\components\bases\BaseController
{

    /**
     * 首页
     */

    public function actionIndex()
    {
        $search_data = \Yii::$app->request->get();
        $class_manage = ClassManage::find()->where(['is_old' => 0, 'is_delete' => 0, 'type' => 1])->indexBy('class_id')->orderBy('class_id DESC ');
        if (!empty($search_data['course'])) {
            $Class_ids1 = ClassManageAttribute::find()->select('class_id')->where(['like', 'course', $search_data['course']])->column();
            $class_manage->andWhere(['in', 'class_id', $Class_ids1]);
        }
        if (!empty($search_data['teacher'])) {
            $Class_ids2 = ClassManageTeacher::find()->select('class_id')->where(['like', 'teacher_name', $search_data['teacher']])->column();
            $class_manage->andWhere(['in', 'class_id', $Class_ids2]);
        }
        if (!empty($search_data['mechanic'])) {
            $mechanic_ids = Mechanic::find()->select('id')->where(['like', 'name', $search_data['mechanic']])->column();
            $class_manage->andWhere(['in', 'mechanic_id', $mechanic_ids]);
        }
        if (!empty($search_data['classroom'])) {
            $class_ids3 = ClassManageAttribute::find()->select('class_id')->where(['like', 'value', $search_data['classroom']])->column();
            $class_manage->andWhere(['in', 'class_id', $class_ids3]);
        }
        if(!empty($search_data['class_date'])){
            $start_time = strtotime($search_data['class_date']);
            $end_time = strtotime($search_data['class_date'])+86400;
            $class_ids4 = ClassLesson::find()->select('class_id')->where(['between','class_date',$start_time,$end_time])->groupBy('class_id')->column();
            $class_manage->andWhere(['in', 'class_id', $class_ids4]);
        }
        if (!empty($search_data['opentime'])) {
            //$day = floor(\Yii::$app->formatter->asTimestamp($search_data['opentime']) / (60 * 60 * 24));
            $min = $start_time = strtotime($search_data['opentime']);
            $max = strtotime($search_data['opentime'])+86400;
            $class_manage->andWhere(['between', 'start_time', $min, $max]);
        }
        if (isset($search_data['status']) && $search_data['status'] != null) {
            $class_manage->andWhere(['status' => $search_data['status']]);
        }
//        //上课时间
//        if (!empty($search_data['start_time'])) {
//            $goods_id4 = GoodsClassTime::find()->select('goods_id')->where(['start_time' => $search_data['start_time']])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_id4]);
//        }
//        if (isset($search_data['cate']) && $search_data['cate'] != null) {
//            $cate_ids = Cate::find()->select('id')->where(['parent_id'=>$search_data['cate']])->column();
//            $goods_id5 = Goods::find()->select('id')->where(['cat_id'=>$cate_ids])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_id5]);
//        }
////        $openClassModel = ClassManage::find()->where(['status' => 1, 'is_old' => 0]);
        $mids = Fun::getMechanicIds();
        if ($mids) {
            $class_manage->andWhere(['mechanic_id' => $mids]);
//            $openClassModel->andWhere(['mechanic_id' => $mids]);
        }
        $auth = \Yii::$app->authManager;
        $roles = $auth->getRolesByUser(\Yii::$app->user->id);
        $arr = [];
        if(!empty($roles)){
            foreach ($roles as $item){
                $arr[] = $item->name;
            }
        }
        if (in_array('business_director',$arr)) {
            $ids = Mechanic::find()->select('id')->where(['admin_id' => \Yii::$app->user->id])->column();
            $class_manage->andWhere(['mechanic_id' => $ids]);
//            $openClassModel->andWhere(['mechanic_id' => $ids]);
        }
        //广场负责人
        if(in_array('class_director',$arr)) {
            $admin_id = \Yii::$app->user->id;
            $mechanic_id = Mechanic::find()->select('id')->where(['admin_id'=>$admin_id,'is_delete'=>0])->column();
            $class_manage->andWhere(['mechanic_id' => $mechanic_id]);
        }
        //老师看属于自己的班级、老师查看自己的班级
       // $role = isset(\Yii::$app->user->identity->role) ? \Yii::$app->user->identity->role : '';
        if(in_array('teache_teacher',$arr)) {
            $class_ids4 = ClassManageTeacher::find()->select('class_id')->where(['teacher_id' => \Yii::$app->user->identity->teacher_id])->column();
            $class_manage->andWhere(['in', 'class_id', $class_ids4]);
        }
        if(in_array('class_teacher',$arr)) {
            $teacher = Teacher::find()->select('id')->where(['parent_id' => \Yii::$app->user->identity->teacher_id])->column();
            $teacher_ids = array_push($teacher, \Yii::$app->user->identity->teacher_id);
            $class_ids5 = ClassManageTeacher::find()->select('class_id')->where(['teacher_id' => $teacher_ids])->column();
            $class_manage->andWhere(['in', 'class_id', $class_ids5]);
        }
        $pages = new Pagination(['totalCount' => $class_manage->count(), 'pageSize' => 10, 'params' => array_merge($_GET, $search_data)]);
        $class_manage = $class_manage->offset($pages->offset)->limit($pages->limit)->all();
        $manageList = Fun::asArray($class_manage, ['course_name', 'classroom_name', 'teacher_name', 'opening_number', 'mechanic_name', 'max_number', 'student_count', 'status_name', 'class_time', 'start_day', 'newoperate']);
        //        $openClass = $openClassModel->all();


        $cates = Cate::find()->where(['parent_id' => 0])->all();
        $cate = [];
        foreach ($cates as $k => $v) {
            $cate[$v->id] = $v->name;
        }
        return $this->render('index', ['data' => $manageList, 'pages' => $pages, 'cate' => $cate]);
    }

    public function actionUpdate()
    {
        $class_id = \Yii::$app->request->get('id');
        if ($class_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $modelManage = ClassManage::findOne($class_id);
        if ($modelManage == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassManageAttribute::find()->where(['class_id' => $class_id])->one();

        $teacherIds = CateRelation::find()->select('object_id')->where(['cate_id' => $model->courses->category_id, 'type' => 1])->column();
        $modelTeacher = Teacher::find()->where(['mechanic_id' => $modelManage->mechanic_id, 'id' => $teacherIds])->all();
        $teacherList = ArrayHelper::map($modelTeacher, 'id', 'name');

        $roomIds = CateRelation::find()->select('object_id')->where(['cate_id' => $model->courses->category_id, 'type' => 2])->column();
        $modelRoom = Classroom::find()->where(['id' => $roomIds, 'state' => 1])->all();
        $roomList = ArrayHelper::map($modelRoom, 'id', 'name');


        return $this->render('update', ['model' => $model, 'teacherList' => $teacherList, 'roomList' => $roomList]);
    }

    /**
     * 学员列表->打卡
     */
    public function actionDetails()
    {

        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_manage = ClassManage::findOne([\Yii::$app->request->get('id')]);
        if ($class_manage === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student_list = ClassStudent::find()->where(['class_manage_id' => $class_manage->class_id,'status'=>[1,0,6]])->all();
        $student_list = Fun::asArray($student_list,['student_name','customer_name','tel','card_id','studentcheck','lesson_num']);
        foreach ($student_list as $key=>$item){
            $student_list[$key]['is_end'] = 0;
            $check = StudentCheck::find()->where(['class_student_id'=>$item['id']])->orderBy('class_lesson_id DESC')->one();
            if($check != null) {
                $rowLesson = ClassLesson::findOne($check->class_lesson_id);
                if (time() > $rowLesson->class_date) {
                    $student_list[$key]['is_end'] = 1;
                }
            }

        }
        return $this->render('details', ['details' => $student_list, 'class_id' => \Yii::$app->request->get('id')]);
    }


    //生成签到

    public function actionGeneratecheck()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $class_id = \Yii::$app->request->get('class_id');
        if ($id == null || $class_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $ClassManager = ClassManage::findOne($class_id);
        if ($ClassManager == null || $ClassManager->status == 0) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '班级不存在或者班级未开班'));
        }
        $model = ClassStudent::findOne($id);
        $model->scenario = 'generatecheck';
        $model->types = 1;
        $class_count = 6;
        $orderRelation = OrdersItemsRelation::find()->where(['orders_items_id' => $model->order_sales_id])->one();
        if ($orderRelation != null) {
            $class_count = $orderRelation->lesson;
        }
        $numArr = range(1, $class_count);
        rsort($numArr);
        $numArrs = [];
        foreach ($numArr as $val) {
            $numArrs[$val] = $val;
        }

//        $surname = ClassStudent::find()->where(['status'=>5,'student_id'=>$model->student_id,'class_manage_id'=>$model->class_manage_id])->one();


        //$classattr = ClassManageAttribute::find()->where(['class_id'=>$class_id])->one();
        //$goods_time_array = ClassManageTime::find()->where(['class_id'=>$class_id])->all();
        $okLesson = [];
        $okList = ClassLesson::find()->where(['class_id' => $class_id,'status'=>[0,1]])->andWhere(['<', 'class_date', time()])->orderBy('lesson ASC')->all();
        if ($okList != null) {
            foreach ($okList as $val) {
                $okLesson[$val->lesson_id] = date('Y-m-d',$val->class_date) . '-第' . $val->lesson . '节';
            }
        }
        //ksort($okLesson);
        $classAttr = ClassManageAttribute::find()->where(['class_id'=>$class_id])->one();
        $timeList = ClassManageTime::find()->where(['class_id' => $class_id])->all();
        $strtime = '';
        foreach ($timeList as $tt){
            $strtime = Util::getWeek($tt->class_day).' '.$tt->start_time.'-'.$tt->end_time;
        }
        $lessonList = ClassLesson::find()->where(['class_id' => $class_id,'status'=>[0,1]])->andWhere(['>=', 'class_date', time()])->orderBy('lesson ASC')->limit(5)->all();
        $lessonLists = [];
        foreach ($lessonList as $val) {
            $lessonLists[$val->lesson_id] =  date('Y-m-d',$val->class_date) . '-第' . $val->lesson . '节';
        }

        $maxLesson = ClassLesson::find()->where(['class_id' => $class_id,'status'=>[0,1]])->orderBy('lesson DESC')->limit(1)->one();
//        $newLesson = [];
//        $addstart_time = 0;
//        if(count($lessonList) < 5) {
//            $x = 1;
//            $j = 0;
//            $addlesson = $maxLesson->lesson + 1;
//            while ($j < 1) {
//                $time = $maxLesson->class_date + 86400 * $x;
//                $class_today = date('w', $time);
//                if ($class_today == 0) {
//                    $class_today = 7;
//                }
//
//                foreach ($timeList as $t) {
//                    if ($t->class_day == $class_today) {
//                        $newLesson['add'] = date('Y-m-d', $time) . "-第" . $addlesson . "节";
//                        $addstart_time = $time;
//                        $j++;
//                        break;
//                    }
//                }
//                $x++;
//            }
//        }

        $lessonLists = $okLesson + $lessonLists;
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            //die;
            $class_count = isset($model->num) ? $model->num : $class_count;
            $orderItem = OrdersItems::findOne($model->order_sales_id);
            $ClassManageAttribute = ClassManageAttribute::find()->where(['class_id' => $class_id])->one();
            if($model->types == 1){
                if ($model->lesson_id == null) {
                    throw new BadRequestHttpException(\Yii::t('zhtfrontend', '数据错误请重试！'));
                }
                $modelLesson = ClassLesson::findOne((int)$model->lesson_id);
                $start_time = $modelLesson->class_date;
                $surplusCount = ClassLesson::find()->where(['class_id' => $class_id,'status'=>[0,1]])->andWhere(['>=', 'lesson', (int)$modelLesson->lesson])->count();
            }else{
                $surplusCount = 0;
                $s = explode(':', Util::getTime($maxLesson->start_time));
                $start_time = strtotime($model->start) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
            }

            //此课次后的课次数小于预约课次增加课次
            if ($surplusCount < $class_count) {
                $newLesson = $class_count - $surplusCount;
                $ovo = 0;
                if ($ClassManageAttribute->teacher_form == 0) {
                    $ovo = 1;
                }
                $i = 1;
                $j = 1;
                $c = 0;
                $x = 0;
                $z = 0;
                while ($j <= $newLesson) {
                    if($model->types == 1){
                        $times = $maxLesson->class_date + 86400 * $i;
                        if($ClassManager->cycle > 0){
                            $times = $times+($ClassManager->cycle+$c)*7*86400;
                        }
                    }else{
                        $times = $start_time+ 86400 * $x;
                        if($ClassManager->cycle > 0) {
                            if ($j > 1) {
                                $times = $times + ($ClassManager->cycle + $z) * 7 * 86400;
                            } else {
                                $times = $times;
                            }
                        }
                    }
                    $class_today = date('N', $times);
                    foreach ($timeList as $t) {
                        if ($t->class_day == $class_today) {
                            $insertLesson[] = [
                                'class_id' => $maxLesson->class_id,
                                'class_date' => $times,
                                'start_time' => $maxLesson->start_time,
                                'end_time' => $maxLesson->end_time,
                                'lesson' => $maxLesson->lesson + $j,
                                'title' => $maxLesson->title,
                                'status' => 0,
                                'ovo' => $ovo,
                                'lesson_type' => isset($orderItem->orders->order_type) ? $orderItem->orders->order_type : '',
                            ];
                            if($j >1){
                                $z++;
                            }
                            $j++;
                            $c++;

                        }
                    }
                    $i++;
                    $x++;
                }

                Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo', 'lesson_type'], $insertLesson)->execute();
            }

            //插入签到以及日志
            if($model->types == 1){
                $lessonList = ClassLesson::find()->where(['class_id' => $class_id,'status'=>[0,1]])->andWhere(['>=', 'lesson', (int)$modelLesson->lesson])->orderBy('lesson ASC')->limit($class_count)->all();//获取大于等于次节课的课次
            }else{
                $lessonList = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['>', 'lesson_id', (int)$maxLesson->lesson_id])->orderBy('lesson_id ASC')->limit($class_count)->all();
            }
            $z = 0;
            $end_time = 0;
            $insertCheckAttr = [];
            $lesson_students = [];
            foreach ($lessonList as $k => $lesson) {
                $status = 0;
                $created_at = 0;
                $insertCheckAttr[] = [
                    'class_student_id' => $model->id,
                    'order_sales_id' => $model->order_sales_id,
                    'student_id' => $model->student_id,
                    'status' => $status,
                    'created_at' => $created_at,
                    'class_lesson_id' => $lesson->lesson_id,
                    'lesson_type' => $lesson->lesson_type,
                ];
                $lesson_students[] = [
                    'lesson_id' => $lesson->lesson_id,
                    'check_time' => $created_at,
                    'student_id' => $model->student_id,
                    'status' => $status,
                ];
                if ($z == ($class_count-1)) {
                    $s = explode(':', Util::getTime($maxLesson->end_time));
                    $end_time = strtotime(date('Y-m-d', $lesson->class_date)) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                    break;
                }
                $z++;

            }
            $model->status = 1;
            $model->start_time = $start_time;
            $model->end_time = $end_time;
            $model->save(false);

            Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id', 'lesson_type'], $insertCheckAttr)->execute();
            Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'check_time', 'student_id', 'status'], $lesson_students)->execute();

//            $MechanicSubsidy = MechanicSubsidy::find()->where(['class_id'=>$model->class_id,'mechanic_id'=>$model->mechanic_id])->orderBy('lesson ASC')->all();
//            foreach ($MechanicSubsidy as $items){
//                $items->class_date = $lessonList[$items->lesson]['class_date'];
//                $items->save(false);
//            }

//            $Student = Student::find()->where(['id' => $model->student_id])->one();
//            $auth = LoginAuth::findOne(['user_id' => $Student->customer_id, 'web_site_id' => 17]);
//            if ($auth != null) {
//                $options = \Yii::$app->params['options_zht'];
//                $app = new Application($options);
//                $title = '开班通知';
//                $name = $ClassManageAttribute->course;
//                $date = date('Y-m-d', $model->start_time);
//                $time = '';
//                foreach ($timeList as $t) {
//                    $time .= Util::getWeek($t['class_day']) . $t['start_time'] . '-' . $t['end_time'] . ' ';
//                }
//                $desc = "课程名称：$name \n 开班日期：$date \n 上课时间：$time";
//                $url = \Yii::$app->params['zhtwechat_url'] . '/appointment/index?customer_id=' . $auth->user_id . '&site_id=' . Fun::getSiteId();
//                $news = new News([
//                    'title' => $title,
//                    'description' => $desc,
//                    'url' => $url
//                ]);
//                $app->staff->message([$news])->to($auth->source_id)->send();
//            }

            return $this->redirectMessage(\Yii::t('zhtfrontend', '生成签到成功'), Fun::url(['newclassmanage/details', 'id' => $class_id]));
        }
        $row = StudentCheck::find()->select(['class_lesson_id','lesson','class_id'])->joinWith('classlesson')->where(['dmd_class_lesson.class_id'=>$model->class_manage_id,'dmd_student_check.student_id'=>$model->student_id])->orderBy('dmd_class_lesson.lesson DESC')->limit(1)->asArray()->one();
        if(!empty($row)){
           $startLesson =  ClassLesson::find()->where(['>','lesson',$row['lesson']])->andWhere(['class_id'=>$row['class_id'],'status'=>[0,1]])->orderBy('lesson ASC')->limit(1)->one();
           if($startLesson != null){
               $model->lesson_id = $startLesson->lesson_id;
           }
        }

        return $this->render('generatecheck', ['model'=>$model,'lessonLists' => $lessonLists, 'numArr' => $numArrs,'strtime'=>$strtime,'classattr'=>$classAttr,'maxLesson'=>$maxLesson]);


    }

    /**
     * @return string
     * @throws BadRequestHttpException
     * 不限课次生成签到
     */

    public function actionGenerateterm(){
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $class_id = \Yii::$app->request->get('class_id');
        if ($id == null || $class_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $ClassManager = ClassManage::findOne($class_id);
        if ($ClassManager == null || $ClassManager->status == 0) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '班级不存在或者班级未开班'));
        }
        $model = ClassStudent::findOne($id);
        $model->start_time = date('Y-m-d',$ClassManager->start_time);
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $itemRelation = OrdersItemsRelation::find()->where(['orders_items_id'=>$model->order_sales_id])->one();
            $start_time = strtotime($model->start_time);
            $i = $itemRelation->deadline;
            if($itemRelation->deadline_type == 'year'){
                $end_time = strtotime("+".$i."year",$start_time);
            }else{
                $end_time = strtotime("+".$i."month",$start_time);
            }
            $model->start_time = $start_time;
            $model->end_time = $end_time;
            $model->status = 1;
            $model->save(false);
            return $this->redirectMessage(\Yii::t('zhtfrontend', '生成签到成功'), Fun::url(['newclassmanage/details', 'id' => $class_id]));
        }

        return $this->render('generateterm',['model'=>$model]);
    }

    /**
     *  锁定/解锁
     */
    public function actionLock()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassStudent::findOne($id);

        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            if ($model->is_lock == 1) {
                $model->is_lock = 0;
                $model->status = 0;
            } else {
                $model->is_lock = 1;
                $model->status = 6;
            }
            $model->remark = $model->remark . "\n" . date('Y-m-d H:i:s', time());

            $model->save(false);
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作成功！'), Fun::url(['newclassmanage/details', 'id' => $model->class_manage_id]));
        }

        return $this->render('lock', ['model' => $model]);
    }

    /**
     *  调班
     */
    public function actionTransfer()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }

        $model = new ClassmanageTurn();
        $ClassStudentmodel = ClassStudent::findOne($id);
        if ($ClassStudentmodel == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $classModel = ClassManage::findOne($ClassStudentmodel->class_manage_id);
        if ($classModel == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $itemReltion = OrdersItemsRelation::find()->where(['orders_items_id' => $ClassStudentmodel->order_sales_id])->one();
        $class_count = $itemReltion->lesson;
//        $okCount = 0;
//        $lessonIds = ClassLesson::find()->select('lesson_id')->Where(['class_id' => $ClassStudentmodel->class_manage_id])->column();
//        if ($ClassStudentmodel->start_time > 0) {
//            $okCount = ClassLesson::find()->where(['between', 'class_date', $ClassStudentmodel->start_time, time()])->andWhere(['class_id' => $ClassStudentmodel->class_manage_id])->count();
//            $lessonIds = ClassLesson::find()->select('lesson_id')->where(['>', 'class_date', time()])->andWhere(['class_id' => $ClassStudentmodel->class_manage_id])->column();
//        }
//        $surplusLesson = $class_count - $okCount; //可转课次
        $latelyLesson = ClassLesson::find()->where(['class_id'=>$classModel->class_id])->andWhere(['>','class_date',time()])->orderBy('lesson_id ASC')->limit($class_count)->one();
        $latelyLesson_id= 0;
        if($latelyLesson != null){
            $latelyLesson_id = $latelyLesson->lesson_id;
        }
        $model->cover_lesson = $latelyLesson_id;
        $coverLessonList = (new \yii\db\Query())->select(['l.lesson_id','l.lesson','l.class_date'])
                         ->from('{{%student_check}} sc')
                         ->leftJoin('{{%class_lesson}} l','sc.class_lesson_id = l.lesson_id')
                         ->where(['sc.class_student_id'=>$ClassStudentmodel->id])
                         ->orderBy('l.lesson ASC')
                         ->all(Fun::getSiteDb());
//        $coverLessonList = ClassLesson::find()->where(['class_id' => $ClassStudentmodel->class_manage_id])->orderBy('lesson_id ASC')->all();
        if(!empty($coverLessonList )) {
            foreach ($coverLessonList as $item) {
                $coverLessonLists[$item['lesson_id']] = date('Y-m-d',$item['class_date']).'第' . $item['lesson'] . '节';
            }
        }else{
            $coverLessonLists = ['1'=>'第1节课'];
        }
//        if ($surplusLesson <= 0) {
//            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '课已上完不能调了'));
//        }
        $classAttr = ClassManageAttribute::find()->where(['class_id' => $classModel->class_id])->one();
        $classIds = ClassManageAttribute::find()->select('class_id')->where(['course_id' => $classAttr->course_id, 'price' => $classAttr->price])->andWhere(['!=', 'id', $classAttr->id])->column();

        $inclass = ClassManage::find()->where(['class_id' => $classIds, 'status' => [0, 1], 'mechanic_id' => $classModel->mechanic_id])->all();
        $inclassList = Fun::asArray($inclass, ['status_name', 'teacher_name', 'class_time', 'course_name']);
        $arr = [];
        if ($inclassList) {
            foreach ($inclassList as $class) {
                $arr[$class['class_id']] = $class['course_name'] . '-' . $class['teacher_name'] . '-' . $class['class_time'] . '-' . $class['status_name'];
            }
        }
        if (\Yii::$app->request->post('ajax') == 'newclass' && \Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $class_id = \Yii::$app->request->post('newclass_id');
            $newClass = ClassManage::findOne($class_id);
            if ($newClass->status == 0) {
                return ['status' => 1, 'content' => '', 'lessonList' => [['lesson_id'=>1,'lesson'=>1,'date'=>'']]];
            } else {
                $lessonList = ClassLesson::find()->where(['class_id' => $class_id,'status'=>[1,0]])->orderBy('lesson ASC')->all();
                $lessonLists = [];
                if($lessonList != null){
                    foreach ($lessonList as $item){
                        $row = [
                            'lesson_id' =>$item->lesson_id,
                            'lesson' =>$item->lesson,
                            'date' =>date('Y-m-d',$item->class_date)
                         ];
                        $lessonLists[] = $row;
                    }
                }
                return ['status' => 1, 'content' => 'ok！', 'lessonList' => $lessonLists];
            }
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $cover_lesson = $model->cover_lesson;
            $student = Student::findOne($ClassStudentmodel->student_id);
            $model->customer_id = $student->customer_id;
            $model->student_id = $student->id;
            $model->old_class_manage_id = $ClassStudentmodel->class_manage_id;
            $model->admin_id = \Yii::$app->user->id;
            if ($model->save(false)) {
                $ClassStudentmodel->status = 3;
                $ClassStudentmodel->end_time = time();
                $ClassStudentmodel->save(false);
                $surplusLesson = $model->num;
                if($classModel->status > 0){
                    $surplusList = ClassLesson::find()->where(['class_id' => $classModel->class_id])->andWhere(['>=', 'lesson_id', $cover_lesson])->all();
//                    $okCount = ClassLesson::find()->where(['class_id' => $classModel->class_id])->andWhere(['<', 'lesson_id', $cover_lesson])->count();
                    $lessonIds = ArrayHelper::getColumn($surplusList, 'lesson_id');
                    StudentCheck::updateAll(['status' => 4, 'created_at' => time()], ['class_student_id' => $ClassStudentmodel->id, 'class_lesson_id' => $lessonIds]); //批量修改签到状态
                    LessonStudent::updateAll(['status' => 3, 'check_time' => time()], ['student_id' => $ClassStudentmodel->student_id, 'lesson_id' => $lessonIds]); //批量修改日志状态
                }
                $newManage = ClassManage::findOne($model->new_class_manage_id);
                $newClassStudent = new ClassStudent();
                $newClassStudent->class_manage_id = $model->new_class_manage_id;
                $newClassStudent->order_sales_id = $ClassStudentmodel->order_sales_id;
                $newClassStudent->student_id = $ClassStudentmodel->student_id;
                $newClassStudent->status = 0;
                $newClassStudent->start_time = 0;
                $newClassStudent->end_time = 0;
                $newClassStudent->is_deposit = 0;
                $newClassStudent->mode = 'A';
                $newClassStudent->save(false);
                if($newManage->status == 1) {
                    $newClassLesson = ClassLesson::findOne((int)$model->lesson);
                    $start_time = $newClassLesson->class_date;
                    $newsurplusLessonCount = ClassLesson::find()->where(['class_id' => $model->new_class_manage_id,'status'=>[0,1]])->andWhere(['>=', 'lesson', $newClassLesson->lesson])->count();
                    $orderItem = OrdersItems::findOne($ClassStudentmodel->order_sales_id);
                    if ($newsurplusLessonCount < $surplusLesson) {
                        $newaddlesson = $surplusLesson - $newsurplusLessonCount;
                        $newMaxLesson = ClassLesson::find()->where(['class_id' => $model->new_class_manage_id])->orderBy('lesson_id DESC')->one();
                        $timeList = ClassManageTime::find()->where(['class_id' => $model->new_class_manage_id])->all();
                        $ovo = 0;
                        $ClassManageAttribute = ClassManageAttribute::find()->where(['class_id' => $model->new_class_manage_id])->one();
                        if ($ClassManageAttribute->teacher_form == 0) {
                            $ovo = 1;
                        }
                        $i = 1;
                        $j = 1;
                        $c= 0;
                        while ($j <= $newaddlesson) {
                            $time = $newMaxLesson->class_date + 86400 * $i;
                            $class_today = date('N', $time);
                            foreach ($timeList as $t) {
                                if ($t->class_day == $class_today) {
                                    $times = $time;
                                    if($newManage->cycle > 0 ){
                                        $times = $time+($newManage->cycle+$c)*7*86400;
                                    }
                                    $insertLesson[] = [
                                        'class_id' => $newMaxLesson->class_id,
                                        'class_date' => $times,
                                        'start_time' => $newMaxLesson->start_time,
                                        'end_time' => $newMaxLesson->end_time,
                                        'lesson' => $newMaxLesson->lesson + $j,
                                        'title' => $newMaxLesson->title,
                                        'status' => 0,
                                        'ovo' => $ovo,
                                        'lesson_type' => isset($orderItem->orders->order_type) ? $orderItem->orders->order_type : '',
                                    ];
                                    $j++;
                                }
                            }
                            $i++;
                        }
                        Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo', 'lesson_type'], $insertLesson)->execute();
                    }
                    //插入签到以及日志
                    $lessonList = ClassLesson::find()->where(['class_id' => $model->new_class_manage_id,'status'=>[0,1]])->andWhere(['>=', 'lesson', (int)$newClassLesson->lesson])->orderBy('lesson ASC')->limit($surplusLesson)->all();//获取大于等于次节课的课次
                    $z = 1;
                    $end_time = 0;
                    $insertCheckAttr = [];
                    $lesson_students = [];
                    foreach ($lessonList as $k => $lesson) {
                        $status = 0;
                        $created_at = 0;
//                        if ($lesson->class_date <= time()) {
//                            $status = 1;
//                            $created_at = time();
//                        }
                        $insertCheckAttr[] = [
                            'class_student_id' => $newClassStudent->id,
                            'order_sales_id' => $newClassStudent->order_sales_id,
                            'student_id' => $newClassStudent->student_id,
                            'status' => $status,
                            'created_at' => $created_at,
                            'class_lesson_id' => $lesson->lesson_id,
                            'lesson_type' => $lesson->lesson_type,
                        ];
                        $lesson_students[] = [
                            'lesson_id' => $lesson->lesson_id,
                            'check_time' => $created_at,
                            'student_id' => $newClassStudent->student_id,
                            'status' => $status,
                        ];
                        if ($z == $surplusLesson) {
                            $s = explode(':', Util::getTime($lesson->end_time));
                            $end_time = strtotime(date('Y-m-d', $lesson->class_date)) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                            break;
                        }
                        $z++;
                    }
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id', 'lesson_type'], $insertCheckAttr)->execute();
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'check_time', 'student_id', 'status'], $lesson_students)->execute();

                    $newUpdateClassStudent = ClassStudent::findOne($newClassStudent->id);
                    $newUpdateClassStudent->status = 1;
                    $newUpdateClassStudent->start_time = $start_time;
                    $newUpdateClassStudent->end_time = $end_time;
                    $newUpdateClassStudent->save(false);
                }
                return $this->redirectMessage(\Yii::t('zhtfrontend', '调班成功'), Fun::url(['newclassmanage/details', 'id' => $classModel->class_id]));

            }
        }


        return $this->render('transfer', ['model' => $model,'classStudentmodel'=>$ClassStudentmodel,'inclassList' => $arr,'coverLessonLists'=>$coverLessonLists]);
    }


    /**
     * 打卡列表
     */
    public function actionSign()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $classstudent = ClassStudent::findOne($id);
        $list = StudentCheck::find()->joinWith('classlesson')->where(['class_student_id' => $classstudent->id])->orderBy(['lesson'=>SORT_ASC,'lesson_id'=>SORT_ASC])->all();
        $class_lesson = [];
        $i = 0;

        foreach ($list as $v) {
            $cl = ClassLesson::findOne($v->class_lesson_id);
            $class_lesson[$i] = [
                'title' => $cl->title,
                'name' => isset($v->student) ? $v->student->name : '',
                'class_date' => \Yii::$app->formatter->asDate($cl->class_date),
                'end_time' => $cl->end_time,
                'start_time' => $cl->start_time,
                'time' => Fun::getClassTime($cl->start_time, $cl->end_time),
                'lesson' => $cl->lesson,
                'status' => (int)$v->status,
                'lesson_id' => $cl->class_id,
                'student_id' => $v->student_id,
                'class_id' => $classstudent->class_manage_id,
                'class_dates' => $cl->class_date,
                'id' => $v->id,
            ];
            $i++;
        }

        return $this->render('sign', ['details' => $class_lesson,'model'=>$classstudent]);
    }

    /**
     * 保存打卡
     */
    public function actionSignin()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $student_check = StudentCheck::findOne($id);
        $LessonModel = ClassLesson::findOne($student_check->class_lesson_id);

//        $classDate = date('Y-m-d', $LessonModel->class_date);
//        $nowDate = date('Y-m-d', time());
//        if ($classDate !== $nowDate) {
//            $return = ['status' => 2];
//            return json_encode($return);
//        }
//        if ($LessonModel->status == 0) {
//            $LessonModel->status = 1;
//            $LessonModel->save(false);
//        }
        //插入记录表--记录上课
        $lessstudent = LessonStudent::find()->where(['lesson_id' => $LessonModel->lesson_id, 'student_id' => $student_check->student_id])->one();
        $lessstudent->status = 1;
        $lessstudent->check_time = time();

        if ($lessstudent->save(false)) {
            //找到相应记录直接改状态
            $student_check->status = 1;
            $student_check->created_at = time();
            if ($student_check->save(false)) {
                //插入代打卡表---插入代打卡表
                //$student = (new Query())->select('*')->from('{{%student}}')->where(['id' => $student_id])->one(Fun::getSysDb());
                $student = Student::findOne($student_check->student_id);
                $SubstituteCheckModel = new SubstituteCheck();
                $SubstituteCheckModel->userid = \yii::$app->user->id;
                $SubstituteCheckModel->student_id = $student_check->student_id;
                $SubstituteCheckModel->customer_id = $student['customer_id'];
                $SubstituteCheckModel->created_at = time();
                $SubstituteCheckModel->student_check_id = $student_check->id;
                $SubstituteCheckModel->save(false);
                Operclassmanager::AddCheckCount($student_check->id);

                //若打卡超过1/3则往总店招生表插入一条信息
//                $class_num = $LessonModel->lesson;
//                $class_count = ClassLesson::find()->where(['class_id' => $LessonModel->class_id])->count();
//                $class_student = ClassStudent::find()->where(['class_manage_id' => $LessonModel->class_id, 'student_id' => $student_id])->one();
//                $classManage = ClassManage::findone($class_id);
//                $Proportion_number = $class_count / 3;
//                $Mechanic = Mechanic::findOne($classManage->mechanic_id);
//                if ($Mechanic->enrollment_ratio > 0) {
//                    $Proportion_number = ceil($class_count * ($Mechanic->enrollment_ratio / 100));
//                }
//                if ($Proportion_number < $class_num) {
//                    $admissionfee = Admissionfee::find()->where(['student_id' => $student_id, 'class_id' => $class_id, 'class_student_id' => $class_student->id])->one();
//                    if (!$admissionfee) {
//                        $admission = new Admissionfee();
//                        $admission->student_id = $student_id;
//                        $admission->customer_id = !empty($student) ? $student->customer_id : '';
//                        $admission->mechanic_id = !empty($classManage) ? $classManage->mechanic_id : '';
//                        $admission->class_id = $class_id;
//                        $admission->class_student_id = !empty($class_student) ? $class_student->id : '';
//                        $admission->goods_id = !empty($classManage) ? $classManage->associate_id : '';
//                        $admission->site_id = Fun::getSiteId();
//                        $admission->status = '0';
//                        $admission->created_at = time();
//
//                        $mechanic = Mechanic::findone(['id' => $classManage->mechanic_id]);
//                        $goods = Goods::findone(['id' => $classManage->associate_id]);
//                        $classroom = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $classManage->associate_id, 'obj_type' => 'classroom_name'])->one();
//                        $teacher = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $classManage->associate_id, 'obj_type' => 'teacher'])->one();
//                        $customer = Customer::findone(['id' => $student->customer_id]);
//                        $salesman = CardAttr::find()->where(['customer_id' => $student->customer_id])->one();
//
//                        $student_age = date('Y') - $student->age;
//
//                        $admission->mechanic_name = !empty($mechanic) ? $mechanic->name : '';
//                        $admission->goods_name = !empty($goods) ? $goods->name : '';
//                        $admission->admissionfee = !empty($goods) ? $goods->admission_fee : '';
//                        $admission->classroom_id = !empty($classroom) ? $classroom->attribute_id : '';
//                        $admission->classroom_name = !empty($classroom) ? $classroom->value : '';
//                        $admission->teacher_id = !empty($teacher) ? $teacher->attribute_id : '';
//                        $admission->teacher_name = !empty($teacher) ? $teacher->value : '';
//                        $admission->class_date = !empty($LessonModel) ? $LessonModel->class_date : '';
//                        $admission->class_day = !empty($LessonModel) ? date('w', $LessonModel->class_date) : '';
//                        $admission->class_start = !empty($LessonModel) ? $LessonModel->start_time : '';
//                        $admission->class_end = !empty($LessonModel) ? $LessonModel->end_time : '';
//                        $admission->customer_name = !empty($customer) ? $customer->name : '';
//                        $admission->student_name = !empty($student) ? $student->name : '';
//
//                        $admission->cate_id = !empty($goods) ? $goods->cat_id : 0;
//                        $admission->mechanic_area = !empty($mechanic) ? $mechanic->region : '';
//                        $admission->salesman_id = !empty($salesman) ? $salesman->salesman_id : 0;
//                        $admission->student_age = !empty($student_age) ? $student_age : 0;
//
//                        $admission->save(false);
//                    }
//                }

                if ($SubstituteCheckModel->id) {
                    $classManager = ClassManage::findOne($LessonModel->class_id);
                    $strs = '';
                    $teacherArr = ClassManageTeacher::find()->select('teacher_name')->where(['class_id' => $LessonModel->class_id])->column();
                    if (!empty($teacherArr)) {
                        $strs = implode(',', $teacherArr);
                    }
                    $classroom_name = '';
                    $classAttr = ClassManageAttribute::find()->where(['class_id' => $LessonModel->class_id])->one();
                    if ($classAttr != null) {
                        $classroom_name = $classAttr->classroom_name;
                        if ($classAttr->room_type == 1) {
                            $classroom_name = $classAttr->room_group_name . '-' . $classAttr->classroom_name;
                        }
                    }
                    $str = '豆苗朵广场';
                    $str .= '<div style="height: 20px"></div>';
                    $str.="<div class=".'cj-xp'."><h2>" . Html::encode(Fun::getSiteName()) . "</h2>";
                    $str .= "<p>票据编号:<span>" . Html::encode(\Yii::$app->formatter->asTimestamp(time())) . "</span></p><p>开票时间：<span>" . date('Y-m-d') . "</span></p>";
                    $str .= "<p>姓名：<span>" . Html::encode(isset($student->name)?$student->name:'') . "</span></p><p>课程:<span>" . Html::encode($LessonModel->title) . "</span></p>";
                    $str .= "<p>老师:<span>" . Html::encode($strs) . "</span></p><p>上课时间：<span>" . Html::encode(isset($LessonModel->start_time)?Util::getTime($LessonModel->start_time):'') . '-' . Html::encode(isset($LessonModel->end_time)?Util::getTime($LessonModel->end_time):'') . "</span></p>";
                    $str .= "<p>教室：<span>" . Html::encode($classroom_name) . "</span></p><p>注：凭小票进入教学区</p></div>";
//                    $str .= ' <table>
//                                 <tr><td>票据编号:</td><td>' .time() . '</td></tr>
//                                 <tr><td>姓名:</td><td>' . Html::encode($student['name']) . '</td></tr>
//                                 <tr><td>上课日期:</td><td>' . Html::encode(\Yii::$app->formatter->asDate($LessonModel->class_date)) . '</td></tr>
//                                 <tr><td>课程:</td><td>' . Html::encode($LessonModel->title) . '</td></tr>
//                                 <tr><td>老师:</td><td>' . Html::encode($strs) . '</td></tr>
//                                 <tr><td>教室:</td><td>' . Html::encode($classroom_name) . '</td></tr>
//                                 <tr><td>上课时间:</td><td>' . Html::encode(isset($LessonModel->start_time)?Util::getTime($LessonModel->start_time):'') . '-' . Html::encode(isset($LessonModel->end_time)?Util::getTime($LessonModel->end_time):'') .  '</td></tr>
//                                 <tr><td>开票时间:</td><td>' . date('Y-m-d') . '</td></tr>
//                                 <tr><td colspan="2">注：凭小票进入教学区</td></tr>
//                             </table>';
                    $return = ['status' => 1, 'str' => $str];
                    return json_encode($return);
                }
            }
        } else {
            $return = ['status' => 0];
            return json_encode($return);
        }
    }

    /**
     * 请假
     */
    public function actionLeave(){
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = StudentCheck::findOne($id);
        $model->is_makeup = 0;
        $classstudent = ClassStudent::findOne($model->class_student_id);

        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $model->status = 2;
            $model->created_at = time();
            if($model->save(false)){
                return $this->redirectMessage(\Yii::t('zhtfrontend','操作成功！'),Fun::url(['details/details','id'=>$classstudent->class_manage_id]));
            }
        }


        return $this->render('leave', ['model' => $model]);
    }

    public function actionLookleave(){
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if($id == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = StudentCheck::findOne($id);
        return $this->render('lookleave', ['model' => $model]);
    }


    /**
     * 课时详情
     */
    public function actionLesson()
    {
//        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_lesson = ClassLesson::find()->where(['class_id' => \Yii::$app->request->get('id')])->orderBy(['lesson'=>SORT_ASC,'lesson_id'=>SORT_ASC])->all();
        return $this->render('lesson', ['details' => $class_lesson]);
    }

    /**
     *  移除课次
     */
    public function actionRelesson(){
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassLesson::findOne($id);
        if($model == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在！'));
        }
        if($model->delete()){
            return $this->redirectMessage(\Yii::t('zhtfrontend', '移除成功！'), Fun::url(['newclassmanage/lesson', 'id' => $model->class_id]));
        }

    }

    /**
     * 开班
     */
    public function actionOpen()
    {
        $this->layout = '@app/views/layouts/iframe.php';

        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $id = \Yii::$app->request->get('id');
        $model = ClassManage::findOne([$id]);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }

        $model->scenario = 'open';
        $studentCount = ClassStudent::find()->where(['class_manage_id' => $id, 'status' => 0])->count();
        if ($studentCount == 0) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '没有学生暂时不能开班！'));
        }
        $goods_time_array = ClassManageTime::find()->where(['class_id' => $id])->orderBy('class_day,start_time ASC')->asArray()->all();
        if (empty($goods_time_array)) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $classattr = ClassManageAttribute::find()->where(['class_id' => $id])->one();
        if ($classattr == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $student = ClassStudent::find()->where(['class_manage_id' => $model->class_id, 'status' => 0])->orderBy('id asc')->all();
            $ajax_object = new AjaxObject();
            $ajax_object->data = count($student) > 0 ? Fun::asArray($student, ['student_name', 'price', 'age', 'tel', 'card_id']) : [];
            return $ajax_object;
        }
        $class_manage_attr = ClassManageAttribute::findOne(['class_id' => $id]);
        $class_manage_time = ClassManageTime::findOne(['class_id' => $id]);
        if ($class_manage_attr->room_type == 1) {
            $room_type = 1;
            $classrooms = Classroom::find()->where(['classroom_group_id' => $class_manage_attr->room_group_id])->all();
            $classroom = ArrayHelper::map($classrooms, 'id', 'name');
            //排除共享组里面该时段被占用的教室str_replace
            $classroom = [];
            foreach ($classrooms as $k => $v) {
                $classroom_attr_id_no = ClassroomAttr::find()->select('id')
                    ->where(['classroom_id'=>$v->id,'classday'=>$class_manage_time->class_day])
                    ->andWhere(['<=','end_time',str_replace(':','',$class_manage_time->start_time)])
                    ->andWhere(['>=','start_time',str_replace(':','',$class_manage_time->end_time)])
                    ->column();
                $classroom_attr_id = ClassroomAttr::find()->select('id')
                    ->where(['classroom_id'=>$v->id,'classday'=>$class_manage_time->class_day])
                    ->andWhere(['not in','id',$classroom_attr_id_no])
                    ->column();
                $class_ids = ClassManageTime::find()->select('class_id')->where(['classroom_attr_id'=>$classroom_attr_id])->column();
                $class_manage = ClassManage::find()->where(['class_id'=>$class_ids,'status'=>1])->all();
                if(empty($class_manage)){
                    $classroom[$v->id] = $v->name .'-'.$v->room_number;
                }
            }
        } else {
            $room_type = 0;
            $classroom = [];
        }
        //查找管理次班级的所有商品
        $goodsIds = ClassManageGoods::find()->select('goods_id')->where(['class_id' => $id])->column();
        $counts = OrdersItemsRelation::find()->where(['goods_id' => $goodsIds])->max('lesson');
        $model->num = $counts;
        $form = new BuildForm('@app/components/forms/classmanageForm.php');
        $form->loadModel(['classmanage' => $model]);
        $form->setItems('classmanage', 'classroom_id', $classroom);
        $form->setItems('classmanage', 'cycle', [0=>'一周',1=>'两周']);
        //获取班主任
        $classTeacher = ClassManageTeacher::find()->where(['class_id' => $id])->one();
        $teacher = Teacher::findOne($classTeacher->teacher_id);
        $model->headmaster = isset($teacher) ? $teacher->parent_id : 0;

        //查找管理次班级的所有商品
        $goodsIds = ClassManageGoods::find()->select('goods_id')->where(['class_id' => $id])->column();
        $count = OrdersItemsRelation::find()->where(['goods_id' => $goodsIds])->max('lesson');


        //ajax验证
//        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'classmanage-form' && $model->load(\Yii::$app->request->post())) {
//            \Yii::$app->response->format = Response::FORMAT_JSON;
//            return ActiveForm::validate($model);
//        }

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $post = \Yii::$app->request->post();
            $cycle = $model->cycle;
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if (!empty($post['ClassManage']['classroom_id'])) {
                    $classroom = Classroom::findOne($post['ClassManage']['classroom_id']);
                    $class_manage_attr->room_id = $classroom->id;
                    $class_manage_attr->classroom_name = $classroom->name;
                    $class_manage_attr->classroom_number = $classroom->room_number;
                    $class_manage_attr->room_group_id = '';
                    $class_manage_attr->room_type = 0;
                    $class_manage_attr->save(false);
                }
                if ($model->status == 1) {
                    $start_time = 0;
                    $end_time = 0;
                    $diff = 0;
                    $times_week = count($goods_time_array); //每周上课次数
                    //插入class_lesson
                    $startweek = (int)date("N", \Yii::$app->formatter->asTimestamp($model->start_time));
                    $j = 1;
                    $first_week_times = 0;
                    $insert_array = [];
                    $count =  $model->num;
                    $length = $flag = $count + $times_week;
                    $array = $this->getClassLessonArray($length, $goods_time_array);
                    $index = 0;
                    $c = 0;
                    for ($m = 0; $m < $length; $m++) {
//                        $index++;
                        if ($m == 0) {//第一周
                            foreach ($goods_time_array as $k => $v) {
                                if ($startweek > $v['class_day']) {
                                    unset($array[$k]);
                                    $flag--;
                                    $index++;
                                } else {
                                    $s = explode(':', $array[$index + $diff]['start_time']);
                                    if ($j == 1) {
                                        $start_time = strtotime($model->start_time) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60; //开始上课时间
                                    }
                                    $insert_array[$j]['class_id'] = $id;
                                    $insert_array[$j]['class_date'] = strtotime($model->start_time) + ($array[$index + $diff]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                                    $insert_array[$j]['start_time'] = str_replace(':', '', $array[$index + $diff]['start_time']);
                                    $insert_array[$j]['end_time'] = str_replace(':', '', $array[$index + $diff]['end_time']);
                                    $insert_array[$j]['lesson'] = $j;
                                    $insert_array[$j]['title'] = isset($classattr->course) ? $classattr->course : '';
                                    $insert_array[$j]['status'] = 0;
                                    $insert_array[$j]['ovo'] = isset($classattr->teacher_form) ? $classattr->teacher_form : '';

                                    if ($j == $count) {
                                        $dates = strtotime($model->start_time) + ($array[$index + $diff]['class_day'] - $startweek) * 60 * 60 * 24;
                                        $htime = floor($insert_array[$j]['end_time'] / 100) * 3600 + (int)substr($insert_array[$j]['end_time'], 2) * 60;
                                        $end_time = $dates + $htime;
                                    }
                                    $j++;
                                    $first_week_times++;
                                    $diff++;
                                }
                            }
                        } elseif ($m >= $times_week) {
                            if ($count < $flag) {//其他周并且还未将添加的剔除干净
                                array_pop($array);
                                $flag--;
                            } else {
                                $e = explode(':', $array[$j - 1 + $index]['start_time']);
                                $end = explode(':', $array[$j - 1 + $index]['end_time']);
                                $aaa = floor(($j - $first_week_times) % $times_week);
                                $cycle_s = 0;
                                if($cycle > 0){
                                    $cycle_s = $cycle + $c;
                                    $c++;
                                }

                                if ($aaa == 0) {
                                    $time = strtotime($model->start_time) + ((floor(($j - $first_week_times) / $times_week)+$cycle_s) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$e[0] * 60 * 60 + (int)$e[1] * 60;
                                    $en_time = strtotime($model->start_time) + (floor(($j - $first_week_times) / $times_week) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$end[0] * 60 * 60 + (int)$end[1] * 60 ;
                                } else {
                                    $time = strtotime($model->start_time) + ((floor(($j - $first_week_times) / $times_week + 1)+$cycle_s) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$e[0] * 60 * 60 + (int)$e[1] * 60;
                                    $en_time = strtotime($model->start_time) + (floor(($j - $first_week_times) / $times_week + 1) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$end[0] * 60 * 60 + (int)$end[1] * 60;
                                }
                                if ($j == $count) {
                                    $end_time = $en_time;
                                }

                                $insert_array[$j]['class_id'] = $id;
                                $insert_array[$j]['class_date'] = $time;
                                $insert_array[$j]['start_time'] = str_replace(':', '', $array[$j - 1 + $index]['start_time']);
                                $insert_array[$j]['end_time'] = str_replace(':', '', $array[$j - 1 + $index]['end_time']);
                                $insert_array[$j]['lesson'] = $j;
                                $insert_array[$j]['title'] = isset($classattr->course) ? $classattr->course : '';
                                $insert_array[$j]['status'] = 0;
                                $insert_array[$j]['ovo'] = isset($classattr->teacher_form) ? $classattr->teacher_form : '';
                                $j++;
                            }

                        }
                    }
                    $model->start_time = $start_time;
                    $model->end_time = $end_time;
                    $model->save(false);
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo'], $insert_array)->execute();

                    $transaction->commit();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '开班成功'), Fun::url(['newclassmanage/index']));
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage(\Yii::t('zhtfrontend', '开班失败'), Fun::url(['newclassmanage/index']));
            }
        }
        $weekstr = '';
        foreach($goods_time_array as $week){
            $weekstr .= Util::getWeek($week['class_day']).' ';
        }
        return $this->render('open', ['form' => $form->render(), 'room_type' => $room_type, 'model' => $model, 'max_number' => $classattr->max_number,'weekstr'=>$weekstr]);
    }


    /**
     * 关闭班级
     */
    public function actionClose(){
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassManage::findOne($id);
        $lsssonList = ClassLesson::find()->where(['class_id'=>$id,'status'=>0])->all();
        if($lsssonList == null){
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '未开班'));
        }
        $lesssonList = [];
        foreach ($lsssonList as $lesson){
            $lesssonList[$lesson->lesson_id] = '第'.$lesson->lesson.'节';
        }

        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $model->status = 0;
            $model->start_time = 0;
            $model->end_time = 0;
            $model->save(false);
            ClassLesson::updateAll(['status'=>2],'class_id=:class_id AND lesson_id>=:lesson_id',[':class_id'=>$id,':lesson_id'=>$model->lesson_id]);

            return $this->redirectMessage(\Yii::t('zhtfrontend', '关闭课程成功！'), Fun::url(['newclassmanage/index']));
        }

        return $this->render('close', ['model' => $model,'lesssonList'=>$lesssonList]);


    }

    /**
     * 删除
     */
    public function actionDelete()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $id = \Yii::$app->request->get('id');
        $class_manage = ClassManage::findOne(['class_id' => $id]);

        if ($class_manage == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        //判断该课程是否有学生
        $student = ClassStudent::find()->where(['class_manage_id' => $id])->andWhere(['<>', 'status', 3])->all();
        if (!empty($student) && $class_manage->status == 0) {
            return $this->redirectMessage(\Yii::t('zhtfrontend', '该课程已有学生预约或已开班，不能删除'), Fun::url(['classmanage/index']));
        }
        //若没有学生且没开班 则可以删除
        //classmanage
        $class_manage->is_delete = 1;
        if ($class_manage->save()) {
            //若已生成商品把商品下架
            $goodsModel = Goods::findOne($class_manage->associate_id);
            if ($goodsModel != null) {
                $goodsModel->is_shelve = 0;
                $goodsModel->save(false);
            }

        }
        //classlesson
        //ClassLesson::deleteAll(['class_id' => $id]);
        return $this->redirectMessage(\Yii::t('zhtfrontend', '删除成功'), Fun::url(['newclassmanage/index']));

    }

    /**
     * 修改课次状态
     */
    public function actionStatus()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('lesson_id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $lesson_id = \Yii::$app->request->get('lesson_id');
        $model = ClassLesson::findOne($lesson_id);
        $model->scenario = 'status';
        $model->is_delay = 1;
        $model->start_time = (string)$model->start_time;
        $model->end_time = (string)$model->end_time;
        $model->is_delay = 1;
        $model->change_time = date('Y-m-d',$model->class_date);
        $form = new BuildForm('@app/components/forms/classlessonForm.php');
        $form->loadModel(['classmanage' => $model]);
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model->start_time = (int)$model->start_time;
            $model->end_time = (int)$model->end_time;
            if ($model->save(false)) {
                //设置签到表状态
                $checkList = StudentCheck::find()->where(['class_lesson_id'=>$lesson_id,'status'=>0])->all();
                StudentCheck::updateAll(['status'=>$model->status,'created_at'=>time()],['class_lesson_id'=>$model->lesson_id,'status'=>0]);
                LessonStudent::updateAll(['status'=>$model->status,'check_time'=>time()],['lesson_id'=>$model->lesson_id,'status'=>0]);
                //如果是老师请假、停课延课
                if(in_array($model->status,[5,6]) && $model->is_delay == 1){
                    $maxLesson = ClassLesson::find()->where(['class_id'=>$model->class_id,'status'=>[0,1]])->orderBy('lesson DESC')->limit(1)->one();
                    $timeList = ClassManageTime::find()->where(['class_id'=>$model->class_id])->all();
                    $classmanageModel = ClassManage::findOne($model->class_id);
                    $x = 1;
                    $j = 0;
                    $week = 1;
                    if($classmanageModel->cycle > 0){
                        $week =  $classmanageModel->cycle+$week;
                    }
                    $class_date = $maxLesson->class_date + $week*7*86400;
//                    while ($j < 0){
//                        $time = $maxLesson->class_date + 86400 * $x;
//                        $class_today = date('w', $time);
//                        if ($class_today == 0) {
//                            $class_today = 7;
//                        }
//                        foreach ($timeList as $t) {
//                            if ($t->class_day == $class_today) {
//                                $class_date = $time;
//                                $j++;
//                                break;
//                            }
//                        }
//                    }
                    $newLesson = new ClassLesson();
                    $newLesson->class_id = $model->class_id;
                    $newLesson->class_date = $class_date;
                    $newLesson->start_time = $model->start_time;
                    $newLesson->end_time = $model->end_time;
                    $newLesson->lesson = $maxLesson->lesson + 1;
                    $newLesson->title = $model->title;
                    $newLesson->status = 0;
                    $newLesson->ovo = $model->ovo;
                    $newLesson->info = $model->info;
                    $newLesson->product_id = $model->product_id;
                    $newLesson->lesson_type = $model->lesson_type;
                    $newLesson->save(false);

                    if($checkList != null){
                        foreach ($checkList as $check){
                            $newmaxLesson = StudentCheck::find()->joinWith('classlesson')->where(['class_student_id'=>$check->class_student_id])->orderBy('lesson DESC')->limit(1)->one();
                            $nextLesson = ClassLesson::find()->where(['class_id'=>$model->class_id,'status'=>[1,0]])->andWhere(['>','lesson',$newmaxLesson->classlesson->lesson])->orderBy('lesson ASC')->limit(1)->one();
                            $newStudentCheck = new StudentCheck();
                            $newStudentCheck->class_student_id = $check->class_student_id;
                            $newStudentCheck->order_sales_id = $check->order_sales_id;
                            $newStudentCheck->student_id = $check->student_id;
                            $newStudentCheck->status = 0;
                            $newStudentCheck->created_at = 0;
                            $newStudentCheck->class_lesson_id = $nextLesson->lesson_id;
                            $newStudentCheck->lesson_type = $check->lesson_type;
                            $newStudentCheck->save(false);
                            $newStudentCheck = new LessonStudent();
                            $newStudentCheck->lesson_id = $nextLesson->lesson_id;
                            $newStudentCheck->status = 0;
                            $newStudentCheck->student_id = $check->student_id;
                            $newStudentCheck->save(false);
                        }
                    }

                }
                //如果是调课
                if($model->status == 7){
                    $s = explode(':', Util::getTime($model->start_time));
                    $class_date = strtotime($model->change_time) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60; //开始上课时间
                    $newLesson = new ClassLesson();
                    $newLesson->class_id = $model->class_id;
                    $newLesson->class_date = $class_date;
                    $newLesson->start_time = $model->start_time;
                    $newLesson->end_time = $model->end_time;
                    $newLesson->lesson = $model->lesson;
                    $newLesson->title = $model->title;
                    $newLesson->status = 0;
                    $newLesson->ovo = $model->ovo;
                    $newLesson->info = $model->info;
                    $newLesson->product_id = $model->product_id;
                    $newLesson->lesson_type = $model->lesson_type;
                    $newLesson->save(false);
                    if($checkList != null){
                        foreach ($checkList as $check){
                            $newStudentCheck = new StudentCheck();
                            $newStudentCheck->class_student_id = $check->class_student_id;
                            $newStudentCheck->order_sales_id = $check->order_sales_id;
                            $newStudentCheck->student_id = $check->student_id;
                            $newStudentCheck->status = 0;
                            $newStudentCheck->created_at = 0;
                            $newStudentCheck->class_lesson_id = $newLesson->lesson_id;
                            $newStudentCheck->lesson_type = $check->lesson_type;
                            $newStudentCheck->save(false);
                            $newStudentCheck = new LessonStudent();
                            $newStudentCheck->lesson_id = $newLesson->lesson_id;
                            $newStudentCheck->status = 0;
                            $newStudentCheck->student_id = $check->student_id;
                            $newStudentCheck->save(false);
                        }
                    }
                }

                return $this->redirectMessage(\Yii::t('zhtfrontend', '添加成功'), Fun::url(['newclassmanage/lesson','id'=>$model->class_id]));
            } else {
                \Yii::$app->session->setFlash('error', '添加失败');
                return \Yii::$app->response->redirect(Fun::url(['classmanage/index']));
            }

        }
        return $this->render('status', ['form' => $form->render(), 'model' => $model]);
    }

    /**
     *  结束课程
     */
    public function actionEndclass()
    {
        $id = \Yii::$app->request->get('id');
        \Yii::$app->response->format = Response::FORMAT_JSON;
        if ($id == null) {
            return ['status'=>0,'content'=>'错误请求'];
        }
        $model = ClassStudent::findOne($id);
        if ($model == null) {
            return ['status'=>0,'content'=>'错误请求'];
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model->status = 2;
            $model->save(false);
            $result = ClassStudent::find()->where(['status'=>[0,1,6],'class_manage_id'=>$model->class_manage_id])->all();
            if($result == null){
                $classModel = ClassManage::findOne($model->class_manage_id);
                $classModel->status = 2;
                $classModel->save(false);
            }
            $transaction->commit();
            return ['status'=>1,'content'=>'操作成功！'];
        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['status'=>0,'content'=>'操作失败！'];
        }
    }

    /**
     * 修改上课时间
     * 延课
     */
    public function actionUpdateclasstime()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '课次不存在'));
        }
        $model = ClassLesson::findOne($id);
        $model->oldlesson = $model->lesson;
        if ($model == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '课次不存在'));
        }

        $model->scenario = 'updateclasstime';
        $model->class_date = date('Y-m-d',$model->class_date);
        $model->start_time= Util::getTime($model->start_time);
        $model->end_time= Util::getTime($model->end_time);
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $s = explode(':', $model->start_time);
            $class_date = strtotime($model->class_date) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
            $model->class_date = $class_date;
            $model->start_time=(int)str_replace(':', '', $model->start_time);
            $model->end_time=(int)str_replace(':', '', $model->end_time);
            if($model->oldlesson > $model->lesson){
                $list = ClassLesson::find()->where(['class_id'=>$model->class_id])->andWhere(['>=','lesson',$model->lesson])->orderBy('lesson ASC')->all();
                if($list != null){
                    foreach ($list as $val){
                        $val->lesson += 1;
                        $val->save(false);
                    }
                }
            }
            $model->save(false);
            return $this->redirectMessage(\Yii::t('zhtfrontend', '修改成功'), Fun::url(['newclassmanage/lesson','id'=>$model->class_id]));
        }
        return $this->render('updateclasstime', ['model' => $model]);

    }

    //生成课程商品
    public function actionGeneratedgoods()
    {
        $id = \Yii::$app->request->get('class_id');
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            if ($id == null) {
                return ['status' => 0, 'content' => '系统错误刷新页面重试'];
            }
            $transaction = Fun::getSiteDb()->beginTransaction();
            $model = ClassManage::findOne($id);
            $classAttr = ClassManageAttribute::find()->where(['class_id' => $model->class_id])->one();
            $classTime = ClassManageTime::find()->where(['class_id' => $model->class_id])->all();
            $classTeacher = ClassManageTeacher::find()->where(['class_id' => $model->class_id])->all();
            $arr = ['region', 'is_booking', 'class_count', 'max_number', 'opening_number', 'course', 'classroom_number', 'classroom_name', 'suitable_age', 'class_length', 'teacher_form', 'age_group'];
            // if ($model->associate_id == 0) {
            try {
                $modelGoods = new Goods();
                $modelGoods->name = $classAttr->course;
                $modelGoods->sn = 'course' . time();
                $modelGoods->cat_id = isset($classAttr->courses->category_id) ? $classAttr->courses->category_id : 0;
                $modelGoods->type_id = 1;
                $modelGoods->price = $classAttr->price;
                $modelGoods->market_price = $classAttr->price;
                $modelGoods->store = $classAttr->max_number;
                $modelGoods->picture = '';
                $modelGoods->description = isset($classAttr->teachers->description) ? $classAttr->teachers->description : '';
                $modelGoods->content = isset($classAttr->courses->description) ? $classAttr->courses->description : '';
                $modelGoods->is_shelve = 0;
                $modelGoods->is_delete = 0;
                $modelGoods->is_booking = $classAttr->is_booking;
                $modelGoods->is_buy = $classAttr->is_buy;
                $modelGoods->site_id = Fun::getSiteId();
                $modelGoods->mechanic_id = $model->mechanic_id;
                $modelGoods->max_buy = 1;
                $modelGoods->up_at = time();
                $modelGoods->updated_at = $classAttr->updated_at;
                $modelGoods->admin_id = \Yii::$app->user->id;
                $modelGoods->arrangement_id = $classAttr->arrangement_id;
                $modelGoods->is_group = $classAttr->is_group;
                $modelGoods->category_id = isset($classAttr->courses->type_id) ? $classAttr->courses->type_id : 0;
                $modelGoods->teaching_methods = 1;
                $modelGoods->tutor_id = $classAttr->tutor_id;
                $modelGoods->save(false);
                //$model->associate_id = $modelGoods->id;
                //$model->save(false);
                foreach ($classAttr as $key => $val) {
                    if (in_array($key, $arr)) {
                        if ($key == 'region') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '地域', 'value' => $classAttr->region, 'obj_type' => 'region']);
                            $attributes->save(false);
                        }
                        if ($key == 'is_booking') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '是否可预约', 'value' => $classAttr->is_booking, 'obj_type' => 'is_booking']);
                            $attributes->save(false);
                        }
                        if ($key == 'class_count') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '上课次数', 'value' => $classAttr->class_count, 'obj_type' => 'class_count']);
                            $attributes->save(false);
                        }
                        if ($key == 'max_number') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '最满人数', 'value' => $classAttr->max_number, 'obj_type' => 'max_number']);
                            $attributes->save(false);
                        }
                        if ($key == 'opening_number') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '开班人数', 'value' => $classAttr->opening_number, 'obj_type' => 'opening_number']);
                            $attributes->save(false);
                        }
                        if ($key == 'course') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->course_id, 'name' => '课程', 'value' => $classAttr->course, 'obj_type' => 'course']);
                            $attributes->save(false);
                        }
                        if ($key == 'classroom_number') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->room_id, 'name' => '教室编号', 'value' => $classAttr->classroom_number, 'obj_type' => 'classroom_number']);
                            $attributes->save(false);
                        }
                        if ($key == 'classroom_name') {
                            if ($classAttr->room_type == 1) {
                                $room_id = $classAttr->room_group_id;
                                $classroom_name = '1-' . $classAttr->room_group_name;
                            } else {
                                $room_id = $classAttr->room_id;
                                $classroom_name = '0-' . $classAttr->classroom_name;
                            }
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $room_id, 'name' => '教室名称', 'value' => $classroom_name, 'obj_type' => 'classroom_name']);
                            $attributes->save(false);
                        }
                        if ($key == 'suitable_age') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '适合年龄段', 'value' => $classAttr->suitable_age, 'obj_type' => 'suitable_age']);
                            $attributes->save(false);
                        }
                        if ($key == 'age_group') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '年龄段', 'value' => $classAttr->age_group, 'obj_type' => 'age_group']);
                            $attributes->save(false);
                        }
                        if ($key == 'class_length') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '上课时长', 'value' => $classAttr->class_length, 'obj_type' => 'class_length']);
                            $attributes->save(false);
                        }
                        if ($key == 'teacher_form') {
                            $attributes = new GoodsAttr(['goods_id' => $modelGoods->id, 'attribute_id' => $classAttr->arrangement_id, 'name' => '授课方式', 'value' => $classAttr->teacher_form, 'obj_type' => 'teacher_form']);
                            $attributes->save(false);
                        }
                    }
                }
                foreach ($classTime as $time) {
                    $GoodsTime = new GoodsClassTime();
                    $GoodsTime->goods_id = $modelGoods->id;
                    $GoodsTime->class_day = $time->class_day;
                    $GoodsTime->start_time = $time->start_time;
                    $GoodsTime->end_time = $time->end_time;
                    $GoodsTime->classroom_attr_id = $time->classroom_attr_id;
                    $GoodsTime->save(false);
                }
                foreach ($classTeacher as $teacher) {
                    $GoodsTeacher = new GoodsTeacher();
                    $GoodsTeacher->goods_id = $modelGoods->id;
                    $GoodsTeacher->teacher_id = $teacher->teacher_id;
                    $GoodsTeacher->teacher_name = $teacher->teacher_name;
                    $GoodsTeacher->save(false);
                }

                $classGoods = ClassManageGoods::find()->where(['class_id' => $id])->orderBy('goods_id DESC')->one();
                if ($classGoods != null) {
                    $oldGoods = Goods::findOne($classGoods->goods_id);
                    $goodsPrice = GoodsPrice::find()->where(['goods_id' => $classGoods->goods_id])->all();
                    if ($goodsPrice != null) {
                        foreach ($goodsPrice as $price) {
                            $newGoodsPrice = new GoodsPrice();
                            $newGoodsPrice->goods_id = $modelGoods->id;
                            $newGoodsPrice->price_name = $price->price_name;
                            $newGoodsPrice->lesson = $price->lesson;
                            $newGoodsPrice->lesson_price = $price->lesson_price;
                            $newGoodsPrice->market_price = $price->market_price;
                            $newGoodsPrice->distribution_way = $price->distribution_way;
                            $newGoodsPrice->distribution_proportion = $price->distribution_proportion;
                            $newGoodsPrice->subsidy_type = $price->subsidy_type;
                            $newGoodsPrice->subsidy_money = $price->subsidy_money;
                            $newGoodsPrice->is_scholarship = $price->is_scholarship;
                            $newGoodsPrice->scholarship = $price->scholarship;
                            $newGoodsPrice->admin_id = \Yii::$app->user->id;
                            if ($modelGoods->is_group == 1) {
                                $newGoodsPrice->art_lesson = $price->art_lesson;
                                $newGoodsPrice->art_lesson_price = $price->art_lesson_price;
                                $newGoodsPrice->is_art_scholarship = $price->is_art_scholarship;
                                $newGoodsPrice->art_scholarship = $price->art_scholarship;
                            }
                            $newGoodsPrice->save(false);
                        }
                        $modelGoods->is_shelve = $oldGoods->is_shelve;
                        $modelGoods->deposit = $oldGoods->deposit;
                        $modelGoods->save(false);
                    }
                    $goodsids = ClassManageGoods::find()->select('goods_id')->where(['class_id' => $id])->column();
                    if (!empty($goodsids)) {
                        Goods::updateAll(['is_shelve' => 0, 'is_delete' => 1,'is_buy'=>0], ['id' => $goodsids]);
                    }
                }
                $ClassManageGoods = new ClassManageGoods();
                $ClassManageGoods->class_id = $id;
                $ClassManageGoods->goods_id = $modelGoods->id;
                $ClassManageGoods->created_at = $classAttr->updated_at;
                $ClassManageGoods->save(false);
                $transaction->commit();
                return ['status' => 1, 'content' => '生成商品成功'];
            } catch (Exception $e) {
                $transaction->rollBack();
                return ['status' => 0, 'content' => '生成商品失败'];
            }

//            } else {
//                try {
//                    $modelGoods = Goods::findOne($model->associate_id);
//                    $modelGoods->cat_id = isset($classAttr->courses->category_id) ? $classAttr->courses->category_id : 0;
//                    $modelGoods->type_id = 1;
//                    $modelGoods->price = $classAttr->price;
//                    $modelGoods->market_price = $classAttr->price;
//                    $modelGoods->store = $classAttr->max_number;
//                    $modelGoods->picture = isset($classAttr->teachers->img) ? $classAttr->teachers->img : '';
//                    $modelGoods->description = isset($classAttr->teachers->description) ? $classAttr->teachers->description : '';
//                    $modelGoods->content = isset($classAttr->courses->description) ? $classAttr->courses->description : '';
//                    $modelGoods->is_shelve = 1;
//                    $modelGoods->is_delete = 1;
//                    $modelGoods->is_booking = $classAttr->is_booking;
//                    $modelGoods->is_buy = $classAttr->is_buy;
//                    $modelGoods->site_id = Fun::getSiteId();
//                    $modelGoods->mechanic_id = $model->mechanic_id;
//                    $modelGoods->max_buy = 1;
//                    $modelGoods->updated_at = $classAttr->updated_at;
//                    $modelGoods->admin_id = \Yii::$app->user->id;
//                    $modelGoods->is_group = $classAttr->is_group;
//                    $modelGoods->category_id = isset($classAttr->courses->type_id) ? $classAttr->courses->type_id : 0;
//                    $modelGoods->teaching_methods = 1;
//                    $modelGoods->tutor_id = $classAttr->tutor_id;
//                    $modelGoods->save(false);
//                    foreach ($classAttr as $key => $val) {
//                        if (in_array($key, $arr)) {
//                            if ($key == 'region') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'region'])->one();
//                                $Attr->value = $classAttr->region;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'is_booking') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'is_booking'])->one();
//                                $Attr->value = $classAttr->is_booking;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'class_count') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'class_count'])->one();
//                                $Attr->value = $classAttr->class_count;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'max_number') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'max_number'])->one();
//                                $Attr->value = $classAttr->max_number;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'opening_number') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'opening_number'])->one();
//                                $Attr->value = $classAttr->opening_number;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'teacher') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'teacher'])->one();
//                                $Attr->attribute_id = $classAttr->teacher_id;
//                                $Attr->value = $classAttr->teacher;
//                                $Attr->save(false);
//                            }
////                        if($key == 'course'){
////                            $Attr = GoodsAttr::find()->where(['goods_id'=>$modelGoods->id,'obj_type'=>'course'])->one();
////                            $Attr->attribute_id = $classAttr->course_id;
////                            $Attr->value = $classAttr->course;
////                            $Attr->save(false);
////                        }
//                            if ($key == 'classroom_number') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'classroom_number'])->one();
//                                $Attr->attribute_id = $classAttr->room_id;
//                                $Attr->value = $classAttr->classroom_number;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'classroom_name') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'classroom_name'])->one();
//                                $Attr->attribute_id = $classAttr->room_id;
//                                $Attr->value = $classAttr->classroom_name;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'suitable_age') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'suitable_age'])->one();
//                                $Attr->value = $classAttr->suitable_age;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'class_length') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'class_length'])->one();
//                                $Attr->value = $classAttr->class_length;
//                                $Attr->save(false);
//                            }
//                            if ($key == 'teacher_form') {
//                                $Attr = GoodsAttr::find()->where(['goods_id' => $modelGoods->id, 'obj_type' => 'teacher_form'])->one();
//                                $Attr->attribute_id = $classAttr->teacher_form;
//                                $Attr->value = $classAttr->teacher_form;
//                                $Attr->save(false);
//                            }
//                        }
//                    }
//                    GoodsClassTime::deleteAll(['goods_id' => $modelGoods->id]);
//                    foreach ($classTime as $time) {
//                        $GoodsTime = new GoodsClassTime();
//                        $GoodsTime->goods_id = $modelGoods->id;
//                        $GoodsTime->class_day = $time->class_day;
//                        $GoodsTime->start_time = $time->start_time;
//                        $GoodsTime->end_time = $time->end_time;
//                        $GoodsTime->classroom_attr_id = $time->classroom_attr_id;
//                        $GoodsTime->save(false);
//                    }
//                    $transaction->commit();
//                    return ['status'=>1,'content'=>'更新班级成功'];
//                } catch (\Exception $e) {
//                    $transaction->commit();
//                    return ['status'=>0,'content'=>'更新班级失败'];
//                }
//            }
        }


    }

    /**
     *  不限课次的代打卡
     */
    public function actionUnlimitedsign(){
        $this->layout = '@app/views/layouts/iframe.php';
         $id = \Yii::$app->request->get('id');
         $classStudent = ClassStudent::findOne($id);
         $student = Student::findOne($classStudent->student_id);
         $classAttr = ClassManageAttribute::find()->where(['class_id'=>$classStudent->class_manage_id])->one();
         $classIds = ClassManageAttribute::find()->select('{{%class_manage_attribute}}.class_id')->joinWith('cLassmanage')->where(['course_id'=>$classAttr->course_id])->column();
         $checkIds = StudentCheck::find()->select('class_lesson_id')->where(['class_student_id'=>$id])->column();

         $time = strtotime("+1 day");
         $lesson_list = ClassLesson::find()->where(['class_id'=>$classIds])->andWhere(['<','class_date',$time])->andWhere(['not in','lesson_id',$checkIds])->orderBy('class_date ASC')->all();
         if(\Yii::$app->request->isAjax){
             \Yii::$app->response->format = Response::FORMAT_JSON;
             $lesson_id = \Yii::$app->request->get('lesson_id');
             $modelLesson = ClassLesson::findOne($lesson_id);
             //$newLesson = ClassLesson::find()->where(['lesson_id'=>$ids])->all();
             $checkModel = new StudentCheck();
             $checkModel->class_student_id = $id;
             $checkModel->order_sales_id = $classStudent->order_sales_id;
             $checkModel->student_id = $classStudent->student_id;
             $checkModel->status = 1;
             $checkModel->created_at = time();
             $checkModel->class_lesson_id = $lesson_id;
             $checkModel->lesson_type = 'renew';
             $checkModel->save(false);
             $student = Student::findOne($classStudent->student_id);
             $SubstituteCheckModel = new SubstituteCheck();
             $SubstituteCheckModel->userid = \yii::$app->user->id;
             $SubstituteCheckModel->student_id = $classStudent->student_id;
             $SubstituteCheckModel->customer_id = $student->customer_id;
             $SubstituteCheckModel->created_at = time();
             $SubstituteCheckModel->student_check_id = $checkModel->id;
             $SubstituteCheckModel->save(false);

             $LessonStudent = new LessonStudent();
             $LessonStudent->lesson_id = $lesson_id;
             $LessonStudent->check_time = time();
             $LessonStudent->status = 1;
             $LessonStudent->student_id = $classStudent->student_id;
             $LessonStudent->save(false);

             $classTeacher = ClassManageTeacher::find()->select('teacher_name')->where(['class_id'=>$modelLesson->class_id])->column();
             $strs = '';
             if(!empty($classTeacher)){
                 $strs = implode(',',$classTeacher);
             }
             $classroom_name = '';
             $classAttr = ClassManageAttribute::find()->where(['class_id' => $modelLesson->class_id])->one();
             if ($classAttr != null) {
                 $classroom_name = $classAttr->classroom_name;
                 if ($classAttr->room_type == 1) {
                     $classroom_name = $classAttr->room_group_name . '-' . $classAttr->classroom_name;
                 }
             }
             $str = '豆苗朵广场';
             $str .= '<div style="height: 20px"></div>';
             $str.="<div class=".'cj-xp'."><h2>" . Html::encode(Fun::getSiteName()) . "</h2>";
             $str .= "<p>票据编号:<span>" . Html::encode(\Yii::$app->formatter->asTimestamp(time())) . "</span></p><p>开票时间：<span>" . date('Y-m-d') . "</span></p>";
             $str .= "<p>姓名：<span>" . Html::encode(isset($student->name)?$student->name:'') . "</span></p><p>课程:<span>" . Html::encode($modelLesson->title) . "</span></p>";
             $str .= "<p>老师:<span>" . Html::encode($strs) . "</span></p><p>上课时间：<span>" . Html::encode(isset($modelLesson->start_time)?Util::getTime($modelLesson->start_time):'') . '-' . Html::encode(isset($modelLesson->end_time)?Util::getTime($modelLesson->end_time):'') . "</span></p>";
             $str .= "<p>教室：<span>" . Html::encode($classroom_name) . "</span></p><p>注：凭小票进入教学区</p></div>";
             $return = ['status' => 1, 'str' => $str];
             return $return;
         }

        return $this->render('unlimitedsign', ['data' => $lesson_list,'id'=>$id,'student'=>$student]);
    }

    /**
     * 增加课次数
     */
    public function actionAddlesson(){
        $this->layout = '@app/views/layouts/iframe.php';
        $class_id = \Yii::$app->request->get('id');
        if ($class_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '数据错误请刷新重试！'));
        }
        $model = ClassManage::findOne($class_id);
        $model->scenario = 'addlesson';
        $model->start_time = '';
        $maxLesson = ClassLesson::find()->where(['class_id'=>$class_id])->orderBy('lesson DESC')->one();
        $timeList = ClassManageTime::find()->where(['class_id' => $class_id])->all();
        $strtime = '';
        foreach ($timeList as $time){
            $strtime .= Util::getWeek($time->class_day).$time->start_time.'-'.$time->end_time;
        }
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            $class_count = $model->num;
            $ClassManageAttribute = ClassManageAttribute::find()->where(['class_id' => $class_id])->one();

            $s = explode(':', Util::getTime($maxLesson->start_time));
            $start_time = strtotime($model->start_time) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
            $ovo = 0;
            if ($ClassManageAttribute->teacher_form == 0) {
                $ovo = 1;
            }
            $j = 1;
            $x = 0;
            $z = 0;
            while ($j <= $class_count) {
                $times = $start_time+ 86400 * $x;
                if($model->cycle > 0) {
                    if ($j > 1) {
                        $times = $times + ($model->cycle + $z) * 7 * 86400;
                    } else {
                        $times = $times;
                    }
                }
                $class_today = date('N', $times);
                foreach ($timeList as $t) {
                    if ($t->class_day == $class_today) {
                        $insertLesson[] = [
                            'class_id' => $maxLesson->class_id,
                            'class_date' => $times,
                            'start_time' => $maxLesson->start_time,
                            'end_time' => $maxLesson->end_time,
                            'lesson' => $maxLesson->lesson + $j,
                            'title' => $maxLesson->title,
                            'status' => 0,
                            'ovo' => $ovo,
                            'lesson_type' => 'renew',
                        ];
                        if($j >1) $z++;
                        $j++;
                    }
                }
                $x++;
            }
            Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo', 'lesson_type'], $insertLesson)->execute();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '添加课次成功'), Fun::url(['newclassmanage/index']));
        }
        return $this->render('addlesson', ['maxLesson' => $maxLesson,'model'=>$model,'strtime'=>$strtime]);
    }

    /**
     * @param $length
     * @param $goods_time_array
     * @return array
     */


    public function getClassLessonArray($length, $goods_time_array)
    {
        $array = [];
        $ids_length = count($goods_time_array);
        for ($i = 0; $i < $length; $i++) {
            if (empty($array)) {
                $array[] = $goods_time_array[0];
            } else {
                $array[] = $goods_time_array[$i % $ids_length];
            }
        }
        return $array;
    }
}